package edu.zut.cs.network.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import edu.zut.cs.network.base.BaseMainCase;

public class Client extends BaseMainCase{
	Socket socket = null;
	int port = 8821;
	OutputStream socketOut = null;
	BufferedReader br = null;

	public Client() throws UnknownHostException, IOException {
		socket = new Socket("127.0.0.1", port);
	}

	public void request() {
		try {
			/*客户端接受服务器消息*/
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String res = br.readLine();
			if (res != null) {
				System.out.println("客户端接收的消息:" + res);
			}
			// 发送消息
			String msg;
			@SuppressWarnings("resource")
			Scanner in=new Scanner(System.in);
			msg=in.nextLine();
			msg = msg + "\r\n";
			socketOut = socket.getOutputStream();
			socketOut.write(msg.getBytes());
			logger.info("客户端已发送消息："+msg);
			
			/* 向服务器发消息 */
			socketOut.flush();
			/*接收服务器返回的是否已发送的消息*/
			res=br.readLine();
			if (res != null) {
				logger.info("客户端接收服务器的消息:" + res);
			}
			logger.info("正在接收数据：");
			JMSConsumerThread jmsConsumerThread=new JMSConsumerThread();//调用消费者
			jmsConsumerThread.consumer();			
			logger.info("接收完毕！");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (socketOut != null) {
				try {
					socketOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
